<template>
  <div class="container">
    <span v-if="!value?.length" class="placeholder">
      {{ placeholder }}
    </span>
    <el-tag v-for="(tag, index) in value" :key="tag" class="tag" closable :disable-transitions="false"
      @close="handleClose(index)">
      {{ tag }}
    </el-tag>
    <el-input v-if="inputVisible" ref="InputRef" v-model="inputValue" @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm" class="tag-input" />
    <el-button v-else link type="primary" @click="showInput">
      设置
    </el-button>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref, defineProps, defineEmits, getCurrentInstance } from 'vue'
import { ElInput, ElMessage } from 'element-plus'

const props = defineProps({
  value: {
    type: Array as () => Array<string>,
    default: () => []
  },
  placeholder: {
    type: String as () => string,
    default: () => '未设置'
  },
  maxSize: {
    type: Number as () => number,
    default: () => 5
  }
})

const emit = defineEmits<{
  (e: 'update:value', value: Array<string>): void;
}>();

const inputValue = ref<string>('')
const inputVisible = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

function handleClose(index: number) {
  emit('update:value', props.value.filter((_, i) => i === index - 1))
}

function showInput() {
  inputVisible.value = true
  nextTick(() => {
    InputRef.value!.input!.focus()
  })
}

function handleInputConfirm() {



  if (props.value.length >= props.maxSize) {
    ElMessage.error(`最多添加${props.maxSize}个`)
    return
  }

  


  if (inputValue.value) {
    emit('update:value', [...props.value, inputValue.value])
  }

  inputVisible.value = false
  inputValue.value = ''
}
</script>


<style lang="less" scoped>
.container {
  // padding: 1px 10px;
  white-space: nowrap;

  .tag {
    margin-right: 10px;
  }

  .placeholder {
    color: #2d5368;
    margin-right: 10px;
    font-size: 12px;
    user-select: none;
  }

  .tag-input {
    display: inline-block;


  }
}
</style>